<template>
  <view class="container">
    <view class="title">
      验证码登录
      <view class="">
        <view class="">欢迎使用大医本正在线问诊医生版</view>
      </view>
    </view>
    <view class="form">
      <view class="formBtm">
        <uni-forms :modelValue="formData" ref="form" label-width="120" label-position="top">
          <uni-forms-item label="" name="">
            <view class="flex-sp-center">
              <image class="icon" src="@/static/my/shouji.png" mode="aspectFit"></image>
              +86
              <view class="shu"></view>
              <uni-easyinput
                type="number"
                v-model="formData.mobile"
                :clearable="false"
                placeholder="请输入您的手机号"
              />
            </view>
          </uni-forms-item>

          <uni-forms-item label="" name="">
            <view class="inputBoxRight flex-sp-center">
              <image class="icon" src="@/static/my/yzm.png" mode="aspectFit"></image>

              <uni-easyinput
                type="number"
                :clearable="false"
                v-model="formData.code"
                placeholder="请输入"
              />
              <text class="right">
                |
                <text class="yzm" @click="startCountDown()">
                  {{ countdown == 60 ? '获取验证码' : countdown }}
                </text>
              </text>
            </view>
          </uni-forms-item>
        </uni-forms>
        <view class="btn" @click="loginMobile('form')">登录/注册</view>
        <!-- <view class="btn" @click="Onekey()">一键登录</view> -->

        <!-- <view class="report flex-sp-center">
          <view class="xian"></view>
          第三方登录
          <view class="xian"></view>
        </view>
        <view class="loginWx">
          <image src="@/static/mine/login/loginWx.png" mode=""></image>
        </view> -->
      </view>
    </view>
    <view class="agreement">
      <radio value="r1" :checked="formData.radio" @click="formData.radio = !formData.radio" />
      登录即同意
      <text class="link" @click="goinfo('pages/login/details/details', 'userAgreement')">
        《服务协议》
      </text>
      和
      <text class="link" @click="goinfo('pages/login/details/details', 'privacyAgreement')">
        《隐私政策》
      </text>
    </view>
    <uni-popup ref="popup">
      <view class="pupBox">
        <view class="pupTitle">
          <view class="xian"></view>
          官方公告
          <view class="xian"></view>
        </view>
        <view class="text">
          <view class="" v-for="n in notice" :key="n.id">
            {{ n.title }}
          </view>
        </view>
        <view class="btn" @click="close()">我知道了</view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { LoginTIM } from '@/utils/TIM'
import { CONFIG } from '@/config/app'
// import {
// 	noticePage,
// } from '@/api/system'
import { loginMobile, sendSmsCode, updatePesence, appPhoneLogin } from '@/api/user'
// #ifdef APP-PLUS
const jpushModule = uni.requireNativePlugin('JG-JPush')
// #endif

export default {
  data() {
    return {
      formData: {
        radio: false,
        mobile: '',
        code: '',
      },
      countdown: 60,
      rules: {
        mobile: {
          rules: [
            {
              required: true,
              errorMessage: '手机号不能为空',
            },
            {
              validateFunction: function (rule, value, data, callback) {
                let iphoneReg = /^1[3-9]\d{9}$/
                if (!iphoneReg.test(value)) {
                  callback('手机号格式不正确，请重新填写')
                }
                return true
              },
            },
          ],
        },
        code: {
          rules: [
            {
              required: true,
              errorMessage: '验证码不能为空',
            },
          ],
        },
      },
      notice: [],
    }
  },
  onLoad() {
    let that = this
    let sysInfo = uni.getSystemInfoSync()
    this.formData.system = sysInfo.system
    this.formData.deviceType = sysInfo.deviceType
    this.formData.deviceId = sysInfo.deviceId
    // this.noticePage()
    // uni.preLogin({
    //   provider: 'univerify',
    //   success() {
    //     that.Onekey()
    //   },
    //   fail(res) {
    //     // 预登录失败

    //     console.log(res.errCode)
    //     console.log(res.errMsg)
    //   },
    // })
  },
  methods: {
    Onekey() {
      console.log(1111)
      var that = this
      uni.login({
        provider: 'univerify',
        univerifyStyle: {
          fullScreen: true,
          backgroundImage: '/static/mine/login/bg.png',
          authButton: {
            normalColor: '#7B66FE', // 授权按钮正常状态背景颜色 默认值：#3479f5
            highlightColor: '#7B66FE', // 授权按钮按下状态背景颜色 默认值：#2861c5（仅ios支持）
            disabledColor: '#7B66FE', // 授权按钮不可点击时背景颜色 默认值：#73aaf5（仅ios支持）
            textColor: '#ffffff', // 授权按钮文字颜色 默认值：#ffffff
            title: '本机号码一键登录', // 授权按钮文案 默认值：“本机号码一键登录”
            borderRadius: '24px', // 授权按钮圆角 默认值："24px" （按钮高度的一半）
          },
          privacyTerms: {
            defaultCheckBoxState: true, // 条款勾选框初始状态 默认值： true
            isCenterHint: false, //未勾选服务条款时点击登录按钮的提示是否居中显示 默认值: false (3.7.13+ 版本支持)
            uncheckedImage: '/static/activity/radio.png', // 可选 条款勾选框未选中状态图片（仅支持本地图片 建议尺寸 24x24px）(3.2.0+ 版本支持)
            checkedImage: '/static/activity/radio2.png', // 可选 条款勾选框选中状态图片（仅支持本地图片 建议尺寸24x24px）(3.2.0+ 版本支持)
            checkBoxSize: 12, // 可选 条款勾选框大小
            textColor: '#BBBBBB', // 文字颜色 默认值：#BBBBBB
            termsColor: '#5496E3', //  协议文字颜色 默认值： #5496E3
            prefix: '我已阅读并同意', // 条款前的文案 默认值：“我已阅读并同意”
            suffix: '并使用本机号码登录', // 条款后的文案 默认值：“并使用本机号码登录”
            privacyItems: [
              // 自定义协议条款，最大支持2个，需要同时设置url和title. 否则不生效
              {
                url: 'https://www.yuanfenjihua.com/privacyAgreement_second.html', // 点击跳转的协议详情页面
                title: '《隐私政策》', // 协议名称
              },
              {
                url: 'https://www.yuanfenjihua.com/UserAgreement_second.html', // 点击跳转的协议详情页面
                title: '《服务协议》', // 协议名称
              },
            ],
          },
        },
        success(res) {
          //预登录成功
          uni.showLoading({
            title: '登录中',
            mask: true,
          })
          uniCloud
            .callFunction({
              name: 'getPhoneNumber', // 你的云函数名称
              data: {
                access_token: res.authResult.access_token, // 客户端一键登录接口返回的access_token
                openid: res.authResult.openid, // 客户端一键登录接口返回的openid
              },
            })
            .then(dataRes => {
              console.log('云函数返回的参数', dataRes)
              appPhoneLogin({
                mobile: dataRes.result.res.phoneNumber,
              }).then(res => {
                console.log(res)
                uni.hideLoading()
                uni.closeAuthView()
                uni.setStorage({
                  key: 'token',
                  data: res.data.accessToken,
                  success: function () {},
                })
                uni.setStorage({
                  key: 'userId',
                  data: res.data.userId.toString(),
                  success: function () {},
                })
                // 登录推送
                that.setJPushAlias(res.data.userId.toString())
                uni.setStorage({
                  key: 'BasicSwitch',
                  data: JSON.stringify(res.data),
                  success: function () {},
                })

                that.changeType(0)
                

                that.TIMLogin()
              })
            })
            .catch(err => {
              console.log('云函数报错', err)
            })
          uni.showToast({
            title: res.authResult,
            icon: 'none',
          })
        },
      })
    },
    // noticePage() {
    // 	noticePage().then(res => {
    // 		if (res.data.list.length > 0) {
    // 			this.notice = res.data.list
    // 			this.$refs.popup.open()
    // 		}
    // 	})
    // },
    close() {
      this.$refs.popup.close()
    },
    setJPushAlias(alias) {
      // #ifdef APP-PLUS
      jpushModule.setAlias(
        {
          alias: alias,
          sequence: 1,
        },
        result => {
          console.log('设置别名结果：', result)
        }
      )
      // #endif
    },
    login() {
      uni.login({
        provider: 'weixin',
        onlyAuthorize: true, // 微信登录仅请求授权认证
        success: function (event) {
          const { code } = event
          //客户端成功获取授权临时票据（code）,向业务服务器发起登录请求。
        },
        fail: function (err) {
          // 登录授权失败
          // err.code是错误码
        },
      })
    },

    startCountDown() {
      if (!this.formData.mobile) {
        uni.showToast({
          title: '请输入手机号',
          icon: 'none',
          duration: 2000,
        })
        return
      }
      if (this.countdown == 60) {
        this.getSendSMSCode()
        let timer = setInterval(() => {
          if (this.countdown > 1) {
            this.countdown--
          } else {
            clearInterval(timer)
            // 清除定时器
            this.countdown = 60
          }
        }, 1000)
      }
    },
    getSendSMSCode() {
      sendSmsCode({
        mobile: this.formData.mobile,
        scene: '1',
      }).then(res => {})
    },
    changeType(e) {
      if (uni.getStorageSync('userId')) {
        updatePesence({
          pesence: e,
        }).then(res => {
          console.log(res)
        })
      }
    },

    loginMobile(ref) {
      var that = this
      if (!this.formData.radio) {
        uni.showToast({
          title: '请勾选《服务协议》和《隐私政策》',
          icon: 'none',
          duration: 2000,
        })
        return
      }
      this.$refs[ref]
        .validate()
        .then(res => {
          uni.clearStorage()
          uni.showLoading({
            title: '登录中',
            mask: true,
          })
          loginMobile(this.formData).then(res => {
            uni.hideLoading()
            uni.setStorage({
              key: 'token',
              data: res.data.accessToken,
              success: function () {},
            })
						if(res.data.role){
							uni.setStorage({
							  key: 'role',
							  data: res.data.role.toString(),
							  success: function () {},
							})
						}
            uni.setStorage({
              key: 'userId',
              data: res.data.userId.toString(),
              success: function () {},
            })
						if (res.data.haveFirstLogin == 1) {
							console.log('第一次登录')
						  uni.navigateTo({
						    url: `/pages/login/authentication/authentication`,
						  })
						} else {
							if (res.data.role == 2) {
							  uni.navigateTo({
							    url: `/pages/Pharmacist/Pharmacist`,
							  })
							} else {
							  this.switchTab()
							}
						}
						

            // 缓存SDKAppID
            uni.$chat_userID = String(res.data.userId)

            // 登录TIM
            LoginTIM(uni.$chat_userID)
						

            // 登录推送
            // this.setJPushAlias(res.data.userId.toString())
						
						

           

            // this.TIMLogin()
          })
        })
        .catch(err => {
          console.log('err', err)
        })
    },
    Back() {
      //uni.navigateBack()//默认delta:1
      uni.navigateBack({
        delta: 1, //返回层数，2则上上页
      })
    },
    goinfo(e, id) {
      if (id) {
        uni.navigateTo({
          url: `/${e}?id=${id}`,
        })
      } else {
        uni.navigateTo({
          url: `/${e}`,
        })
      }
    },
    switchTab() {
      uni.switchTab({
        url: '/pages/index/index',
      })
    },
  },
}
</script>

<style lang="less" scoped>
.container {
  // background-image: url('@/static/mine/login/bg.png');
  background-size: 100% 100vh;
  background-repeat: no-repeat;
  min-height: 100vh;
  padding: 140rpx 60rpx 0;
  box-sizing: border-box;
  background-color: #fff;

  .icon {
    width: 28rpx;
    height: 33rpx;
    margin-right: 14rpx;
  }

  .shu {
    width: 1rpx;
    height: 28rpx;
    background-color: #eeeeee;
    margin-left: 14rpx;
  }

  .pupBox {
    width: 555rpx;
    min-height: 477rpx;
    background: #ffffff;
    border-radius: 30rpx;
    text-align: center;
    padding: 0 35rpx 41rpx;
    box-sizing: border-box;

    .text {
      font-weight: 500;
      font-size: 28rpx;
      color: #999999;
      text-align: left;
    }

    .btn {
      width: 387rpx;
      height: 90rpx;
      background: linear-gradient(103deg, #db88fc 0%, #7b66fe 100%);
      box-shadow: 0rpx 2rpx 6rpx 0rpx rgba(42, 41, 48, 0.35);
      border-radius: 20rpx;
      font-size: 28rpx;
      font-family: PingFang SC;
      font-weight: 500;
      color: #ffffff;
      line-height: 90rpx;
      text-align: center;
      margin-top: 65rpx;
      margin: 46rpx auto 0;
    }

    .pupTitle {
      font-weight: 800;
      font-size: 35rpx;
      color: #3f5a88;
      margin-top: 10rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 16rpx;

      .xian {
        width: 66rpx;
        height: 2rpx;
        background: #3f5a88;
        margin: 0 31rpx;
      }
    }

    image {
      width: 144rpx;
      height: 144rpx;
      margin-top: -31rpx;
    }
  }

  .agreement {
    width: 100%;
    position: fixed;
    left: 0;
    bottom: 67rpx;
    margin-top: 27rpx;
    font-size: 26rpx;
    font-weight: 500;
    color: #999999;
    line-height: 30rpx;
    text-align: center;

    /deep/.uni-radio-input {
      width: 22rpx;
      height: 22rpx;
    }

    .link {
      color: #7b66fe;
    }
  }

  /deep/.uni-forms-item {
    align-items: flex-start;
  }

  .inputBoxRight {
    position: relative;
    margin-bottom: 24rpx;

    .right {
      position: absolute;
      top: 50%;
      right: 20rpx;
      transform: translateY(-50%);
      font-size: 30rpx;
      color: #999999;

      .yzm {
        display: inline-block;
        width: 150rpx;
        text-align: center;
        font-weight: 500;
        font-size: 26rpx;
        color: #7b66fe;
      }
    }

    /deep/.uni-input-wrapper {
      padding-left: 10rpx;
      box-sizing: border-box;
    }

    /deep/.uni-input-placeholder {
      left: 10rpx;
    }
  }

  .loginWx {
    margin-top: 40rpx;
    text-align: center;

    image {
      width: 59rpx;
      height: 59rpx;
    }
  }

  .report {
    font-size: 26rpx;
    font-weight: 500;
    color: #999999;

    .xian {
      width: 209rpx;
      height: 1rpx;
      background-color: #eeeeee;
    }
  }

  .business {
    font-size: 28rpx;
    font-weight: bold;
    text-decoration: underline;
    color: #7b66fe;
    line-height: 28rpx;
    text-align: center;
    margin: 24rpx 0 35rpx;
    margin-right: 30rpx;
  }

  .title {
    font-size: 52rpx;
    font-weight: bold;
    color: #333;
    margin-top: 80rpx;

    & > view {
      view {
        margin-top: 17rpx;
        font-size: 28rpx;
        font-weight: 500;
      }
    }
  }

  .form {
    width: 690rpx;
    min-height: 553rpx;
    // background-image: url(@/static/mine/login/boxBg.png);
    background-size: 100% 100%;
    margin-top: 69rpx;
    margin-bottom: 25rpx;
    border-radius: 20rpx;

    .formTop {
      width: 300rpx;
      height: 87rpx;
      line-height: 87rpx;
      padding-left: 19rpx;
      box-sizing: border-box;
      font-size: 34rpx;
      font-weight: bold;
      text-align: center;
      color: #333333;
      border-radius: 20rpx 20rpx 0 0;
    }

    .uni-forms-item {
      margin-bottom: 22rpx;
    }

    .formBtm {
      padding: 30rpx 0rpx;
      box-sizing: border-box;
      border-radius: 0 20rpx 20rpx 20rpx;

      /deep/.uni-forms-item__content {
        width: 631rpx;
        border-bottom: 1px solid #eeeeee;
      }

      /deep/.uni-easyinput__placeholder-class {
        font-size: 28rpx !important;
      }

      /deep/.is-input-border {
        border: none;
      }

      .btn {
        width: 649rpx;
        height: 90rpx;
        background: #3b6cfe;
        border-radius: 45rpx;
        font-size: 28rpx;
        font-family: PingFang SC;
        font-weight: 500;
        color: #ffffff;
        line-height: 90rpx;
        text-align: center;
        margin-top: 232rpx;
      }

      /deep/.uni-forms-item__label {
        font-size: 28rpx;
        font-weight: 500;
        color: #333333;
      }

      /deep/.uni-easyinput__content {
        height: 91rpx;
        background: #fff !important;
        border-radius: 46rpx;
        font-size: 26rpx;
      }
    }
  }
}
</style>
